package org.suyafei.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.suyafei.model.LoginUser;

import java.util.Date;

/**
 * @author 宿某人
 * @Date: 2021/12/11/10:38 下午
 * @Description:
 */
@Slf4j
public class JWTUtil {


    private static final String SUBJECT = "xiaoyuer";
    private static final String SECRET = "xiaoyuer.net18";
    private static final String TOKEN_PREFIX = "scloud-link";
    /**
     * 过期时间7天
     */
    private static final long EXPIRED = 1000L * 60 * 60 * 24 * 365;



    public static String geneJsonWebToken(LoginUser loginUser) {
        if (loginUser == null) {
            throw new NullPointerException("对象为空");
        }
        String token = Jwts.builder().setAudience(SUBJECT).claim("head_img", loginUser.getHeadImg())
                .claim("account_no", loginUser.getAccountNo())
                .claim("username", loginUser.getUsername())
                .claim("mail", loginUser.getMail())
                .claim("phone", loginUser.getPhone())
                .claim("auth", loginUser.getAuth())
                .setIssuedAt(new Date())
                .setExpiration(new Date(CommonUtil.getCurrentTimestamp() + EXPIRED))
                .signWith(SignatureAlgorithm.HS256, SECRET)
                .compact();
        token = TOKEN_PREFIX + token;

        return token;

    }

    /**
     * 检查JWT
     * @param token
     * @return
     */
    public static Claims checkJWT(String token) {
        try {
            final Claims claims = Jwts.parser().setSigningKey(SECRET).parseClaimsJws(token.replace(TOKEN_PREFIX, "")).getBody();
            return claims;
        } catch (Exception e) {
            log.error("解析JWT失败");
            return null;
        }
    }
}
